<template>

  <div>
    <el-drawer
      :wrapperClosable="false"
      :title="title"
      :visible.sync="open"
      direction="rtl"
      size="38%"
    >

      <el-container>

        <el-main>

          <!-- 表单 -->
          <el-form ref="form" :model="form" :rules="rules" label-width="80px">

            <!-- 组件名称 -->
            <el-form-item label="组件名称" :label-width="shareLabelWidth" prop="name">
              <el-input v-model="form.name" placeholder="请输入组件名称"/>
            </el-form-item>

            <!-- 组件类型-->
            <el-form-item label="组件类型" label-position="left" :label-width="shareLabelWidth" prop="type">
              <el-select
                v-model="form.type"
                :disabled="formDisabledByStartState"
                placeholder="请选择组件类型"
                class="select-width"
              >
                <el-option
                  v-for="dict in networkTypes"
                  :key="dict.id"
                  :label="dict.name"
                  :value="dict.id"
                />
              </el-select>
            </el-form-item>

            <!-- 集群 -->
            <el-form-item label="集群" :label-width="shareLabelWidth" prop="shareCluster">
              <el-row>
                <el-col :span="14">
                  <el-radio-group v-model="form.shareCluster" :disabled="formDisabledByStartState">
                    <el-radio :label="true">共享配置</el-radio>
                    <el-radio :label="false">独立配置</el-radio>
                  </el-radio-group>
                </el-col>
                <el-col :span="10">
                  <el-button
                    v-if="serverIdAddButtonVisible"
                    plain
                    icon="el-icon-plus"
                    size="small"
                    :disabled="formDisabledByStartState"
                    @click="handleAddIndependentConfiguration"
                    v-hasPermi="['iot:network:add']"
                  >新增
                  </el-button>
                </el-col>
              </el-row>
            </el-form-item>

            <!-- 当集群为共享配置时渲染 -->
            <network-configuration
              :form-data="this.form.configuration"
              ref="shareNetworkConfiguration"
              v-if="form.shareCluster"
              :label-width="shareLabelWidth"
              :start-state="form.startState"
              :network-type="form.type"
            />

            <el-row v-if="!form.shareCluster" v-for="(item, index) in this.form.cluster" :style="{'padding-left': `${shareLabelWidth}`}">
              <el-col :span="22">

                <!--   重叠组件 当集群为独立集群时渲染  -->
                <el-collapse>

                  <el-collapse-item :title="item.serverId" :name="item.serverId">

                    <network-configuration
                      :form-data="item.configuration"
                      ref="independentNetworkConfiguration"
                      :label-width="clusterLabelWidth"
                      :start-state="form.startState"
                      :network-type="form.type"
                    />

                  </el-collapse-item>

                </el-collapse>

              </el-col>

              <el-col :span="2" style="margin-top: 8px; padding-left: 20px">
                <!-- 删除配置项 -->
                <el-button :disabled="formDisabledByStartState" @click="handleDeleteIndependentCluster(index)" type="text">
                  <i class="el-icon-remove-outline enum-add-remove-icon"/>
                </el-button>
              </el-col>
            </el-row>

            <!-- 组件描述-->
            <el-form-item
              label="描述"
              prop="description"
              style="margin-top: 8px"
              label-position="left"
              :label-width="shareLabelWidth"
            >
              <el-input v-model="form.description" type="textarea" placeholder="请输入"/>
            </el-form-item>

          </el-form>

        </el-main>

        <el-footer>
          <div class="bottom-bar" style="text-align: right">
            <el-button @click="cancel">取 消</el-button>
            <el-button type="primary" @click="handleSubmit">确 定</el-button>
          </div>
        </el-footer>

      </el-container>
    </el-drawer>

    <!-- 服务id添加表单 -->
    <network-server-id @submit="handleSubmitServerId" ref="networkServerId"/>

  </div>

</template>

<script>

import { addNetwork, getNetwork, getNetworkType, updateNetwork } from '@/api/iot/network'
// configuration 数据配置部分表单
import NetworkConfiguration from './networkConfiguration'
// 服务id添加表单
import NetworkServerId from './networkServerId'


export default {
  name: 'NetworkAddEdit',
  components: {
    NetworkConfiguration,
    NetworkServerId
  },
  computed: {
    // 启动状态为启动的时候使表单不可输入
    formDisabledByStartState() {
      return this.form.startState === 'enabled'
    }
  },
  data() {

    return {
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      shareLabelWidth: '110px',
      clusterLabelWidth: '100px',
      // 表单参数
      form: {
        // 集群选择
        shareCluster: true,
        // 启停状态
        startState: 'disabled',
        configuration : {
          addresses: [],
          host: '0.0.0.0',
          parserConfiguration: {}
        },
        cluster: []
      },

      // 配置新增 默认隐藏
      serverIdAddButtonVisible: false,

      // 组件类型
      networkTypes: [],

      // 表单校验
      rules: {

        name: [
          { required: true, message: '组件名称不能为空', trigger: 'blur' }
        ],
        type: [
          { required: true, message: '组件类型不能为空', trigger: 'blur' }
        ],
        shareCluster: [
          { required: true, message: '集群配置不能为空', trigger: 'blur' }
        ]

      }
    }
  },

  watch: {
    // 集群类型
    'form.shareCluster'(type) {
      this.visibleByShareCluster(type)
    }
  },

  created() {
    // 获取网络组件类型
    this.getNetworkType()
  },

  methods: {
    // 表单重置
    reset() {
      this.form = {
        // 集群选择
        shareCluster: true,
        // 启停状态
        startState: 'disabled',
        configuration : {
          addresses: [],
          host: '0.0.0.0',
          parserConfiguration: {}
        },
        cluster: []
      }
      this.resetForm('form')
    },
    /** 取消按钮操作 */
    cancel() {
      this.open = false
      this.reset()
    },

    /** 新增按钮操作 */
    handleAddNetwork() {
      this.reset()
      this.open = true
      this.title = '添加组件'
    },

    /** 删除独立配置按钮操作 */
    handleDeleteIndependentCluster(index) {
      //删除数组中的一条数据，
      this.form.cluster.splice(index, 1)
    },
    /** 修改按钮操作 */
    handleUpdate(id) {
      getNetwork(id).then(({ data }) => {
        this.title = '修改组件'

        data.configuration = JSON.parse(data.configuration)

        if (data.cluster) {
          data.cluster = JSON.parse(data.cluster)
        }

        this.form = data
        this.open = true
      })
    },
    /** 提交按钮 */
    async handleSubmit() {

      let pass = true;

      await this.childrenFormValidate().then(valid => {
        if (!valid) {
          pass = valid
        }
      })

      await this.$refs['form'].validate(valid => {
        if (!valid) {
          pass = valid
        }
      })

      if (pass) {

        let data = JSON.parse(JSON.stringify(this.form))
        data.configuration = JSON.stringify(this.form.configuration)
        data.cluster = JSON.stringify(this.form.cluster)

        if (this.form.id) {
          updateNetwork(data).then(() => {
            this.$modal.msgSuccess('修改成功')
            this.open = false
            this.$emit('submit')
          })
        } else {
          addNetwork(data).then(() => {
            this.$modal.msgSuccess('新增成功')
            this.open = false
            this.$emit('submit')
          })
        }
      }

    },

    async childrenFormValidate() {

      let pass = true

      if (this.form.shareCluster) {
        const shareNetworkConfiguration = this.$refs.shareNetworkConfiguration;
        if (shareNetworkConfiguration) {
          // 子表单提交
          await shareNetworkConfiguration.handleSubmit().then(valid => pass = valid)
        }
      }else {

        const independentNetworkConfiguration = this.$refs.independentNetworkConfiguration;

        if (!independentNetworkConfiguration) {
          return;
        }

        for (let i = 0; i < independentNetworkConfiguration.length; i++) {
          await independentNetworkConfiguration[i].handleSubmit().then(valid => {
            if (!valid) {
              pass = valid;
            }
          })
        }

      }

      return pass
    },

    /** 新增独立配置按钮操作 */
    handleAddIndependentConfiguration() {
      // 打开服务id添加页面
      this.$refs.networkServerId.handleOpen()
    },
    /** 增加配置的提交按钮 */
    handleSubmitServerId(serverId) {
      this.form.cluster.push({
        serverId: serverId,
        configuration : {
          addresses: [],
          host: '0.0.0.0',
          parserConfiguration: {}
        }
      })
    },

    /**
     * 根据集群配置隐藏显示服务id添加按钮
     * @param type 集群类型
     */
    visibleByShareCluster(type) {
      this.serverIdAddButtonVisible = type === false
    },

    /** 获取网络组件类型 */
    getNetworkType() {
      getNetworkType().then(({ data }) => {
        this.networkTypes = data || []
      })
    }

  }
}
</script>

<style scoped lang="scss">
</style>
